const jwt = require('jsonwebtoken');
const SECRET_KEY = process.env.SECRET_KEY || 'your-default-secret';

module.exports = async (ctx, next) => {
  const authHeader = ctx.headers['authorization'];

  if (!authHeader) {
    ctx.status = 401;
    ctx.body = { code: 401, msg: '缺少授权 token' };
    return;
  }

  const parts = authHeader.split(' ');

  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    ctx.status = 401;
    ctx.body = { code: 401, msg: '无效的 token 格式，应为 Bearer <token>' };
    return;
  }

  const token = parts[1];

  try {
    const payload = jwt.verify(token, SECRET_KEY);
    ctx.state.user = payload; // 保存解码后的用户信息，供后续中间件或控制器使用
    await next();
  } catch (err) {
    console.error('Token 验证失败：', err.message);
    ctx.status = 401;
    ctx.body = { code: 401, msg: 'token 验证失败或已过期' };
  }
};
